﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.Diagnostics;

namespace Rdz.Utility
{
	public class DateUtility
	{
		public static DateTime FirstDateOfWeek(int year, int weekNum, CalendarWeekRule rule)
		{
			Debug.Assert(weekNum >= 1);

			DateTime jan1 = new DateTime(year, 1, 1);

			int daysOffset = DayOfWeek.Monday - jan1.DayOfWeek;
			DateTime firstMonday = jan1.AddDays(daysOffset);
			Debug.Assert(firstMonday.DayOfWeek == DayOfWeek.Monday);

			var cal = CultureInfo.CurrentCulture.Calendar;
			int firstWeek = cal.GetWeekOfYear(jan1, rule, DayOfWeek.Monday);

			if (firstWeek <= 1)
			{
				weekNum -= 1;
			}

			DateTime result = firstMonday.AddDays(weekNum * 7);

			return result;
		}
	}
}
